﻿Imports HtmlAgilityPack
Imports System.Text.RegularExpressions
Imports Kent.Boogaart.KBCsv
Imports System.Linq
Imports NAppUpdate.Framework



Public Class Form1




     
    Dim webtable As rankingDataTable = New rankingDataTable
    Dim localtable As rankingDataTable = New rankingDataTable
    Dim updman As UpdateManager = UpdateManager.Instance
    Dim resulttable As DataTable

    Dim web As HtmlWeb = New HtmlWeb
    Dim doc As HtmlDocument

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click


        If (NumericUpDown2.Value - NumericUpDown1.Value) > 5 Then

            If MsgBox("Retrieving more then 10 pages can take up some time to complete" & _
                      vbCrLf & "Are you sure you want to continue?" _
                      , MsgBoxStyle.OkCancel, _
                      "Are you sure?") = MsgBoxResult.Cancel Then

                setTTSLabel("Done")
                Exit Sub

            End If

        End If
        Label5.Text = Date.Today
        loadrankingpagesfromweb(NumericUpDown1.Value, NumericUpDown2.Value)
        ''populateDataTable()
        setTTSLabel("Done")

    End Sub
    Private Function extractIDfromURL(ByVal URL As String) As String
        Dim lastApo As Integer
        Dim secondIs As Integer


        Dim returnVal As String = String.Empty
        Dim collection As MatchCollection = Regex.Matches(URL, "\d+")

        For Each m As Match In collection
            returnVal += m.ToString()
        Next

        'Return returnVal


        secondIs = URL.LastIndexOf("php&view=")
        lastApo = URL.LastIndexOf(Chr(34))

        Return URL.Substring(secondIs + 9, lastApo - secondIs - 9)

    End Function
    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        setTTSLabel("saving CSV file...")

        SaveFileDialog1.FileName = "data_" + Date.Today + ".csv"
        SaveFileDialog1.Title = "Save Csv file"
        SaveFileDialog1.InitialDirectory = Application.LocalUserAppDataPath
        SaveFileDialog1.Filter = "Csv files|*.csv"
        SaveFileDialog1.ShowDialog()


        setTTSLabel("Done")
    End Sub


    Private Sub populateDataTable()
        setTTSLabel("Filling Table...")
        'webtable.setupDataTable()
        ' below we select all tablerows from the 2nd position and higher in our html document,
        ' inside a nested table table with class name 'std_test' inside a table with the same class name
        For Each link As HtmlNode In doc.DocumentNode.SelectNodes("//table[@class='std_text']//table[@class='std_text']/tr[position() >= 2]  ")
            'TextBox1.AppendText(link.InnerHtml + vbTab + link.GetAttributeValue("bgcolor", "") + "**" + vbCrLf)
            webtable.Rows.Add(link.ChildNodes(1).InnerHtml, link.ChildNodes(3).InnerText, extractIDfromURL(link.ChildNodes(3).InnerHtml), link.ChildNodes(5).InnerText, link.ChildNodes(7).InnerText)
            Application.DoEvents()
        Next

        setupDGview(DataGridView1, webtable)


    End Sub

    ' Loops for a specificied period of time (milliseconds)
    Private Sub wait(ByVal intervalms As Integer)
        Dim sw As New Stopwatch
        sw.Start()
        Do While sw.ElapsedMilliseconds < intervalms
            ' Allows UI to remain responsive
            Application.DoEvents()
        Loop
        sw.Stop()
    End Sub
    Private Sub loadPagefromweb(ByVal pagenumber As Decimal)

        Dim web As HtmlWeb = New HtmlWeb
        doc = web.Load("http://darkspace.net/index.htm?module=ranking.php&offset=" + pagenumber.ToString + "&field_id=0")

    End Sub
    Private Sub setTTSLabel(ByVal text As String)
        If TSProgressBar1.Value = 100 Then TSProgressBar1.Value = 0
        TSProgressBar1.Value += 25

        If text = "done" Or text = "Done" Then
            TSProgressBar1.Value = TSProgressBar1.Maximum

        End If

        TSSLabel1.Text = text
        ' wait(300)
    End Sub

    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
        setTTSLabel("Loading Csv file")


        OpenFileDialog1.Title = "Load Csv file"
        OpenFileDialog1.InitialDirectory = Application.LocalUserAppDataPath
        OpenFileDialog1.Filter = "Csv files|*.csv"
        OpenFileDialog1.ShowDialog()



    End Sub

    Private Sub OpenFileDialog1_FileOk(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles OpenFileDialog1.FileOk

        localtable.loadCSVFileIntoTable(OpenFileDialog1.FileName)
        Dim openfileinfo As IO.FileInfo = New IO.FileInfo(OpenFileDialog1.FileName)

        Label6.Text = openfileinfo.Name
        setupDGview(DataGridView2, localtable)
        'DataGridView2.DataSource = dataset.Tables("csv-data")

        setTTSLabel("Done")
    End Sub

    Private Sub SaveFileDialog1_FileOk(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles SaveFileDialog1.FileOk
        webtable.saveTableToCSVFile(SaveFileDialog1.FileName)
    End Sub

    Private Sub loadrankingpagesfromweb(ByVal startpage As Integer, ByVal endpage As Integer)

        'setupDataTable()
        webtable.setupDataTable()

        Dim offset As Decimal = 0

        Do While startpage <= endpage

            If startpage - 1 = 0 Then
                offset = 0
            Else
                offset = (startpage - 1) * 100
            End If

            setTTSLabel("Loading Page " + startpage.ToString + "...")

            loadPagefromweb(offset)

            populateDataTable()

            startpage += 1
        Loop


    End Sub


    Private Sub NumericUpDown1_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NumericUpDown1.ValueChanged
        If NumericUpDown2.Value < NumericUpDown1.Value Then
            NumericUpDown2.Value = NumericUpDown1.Value

        End If
    End Sub

    Private Sub NumericUpDown2_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NumericUpDown2.ValueChanged
        If NumericUpDown1.Value > NumericUpDown2.Value Then
            NumericUpDown1.Value = NumericUpDown2.Value

        End If
    End Sub

    Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
        If Not DataGridView1.DataSource Is Nothing Then

            If TextBox1.Text.Length > 0 Then

                Dim searchstring As String = TextBox1.Text

                resulttable = New DataTable

                If Not searchInDatatable(webtable, resulttable, "Name", searchstring, True) Then

                    Exit Sub

                End If

                Form2.DataGridView1.DataSource = resulttable
                Form2.DataGridView1.Columns("ID").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
                Form2.DataGridView1.Columns("Prestige").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
                Form2.Show()
            Else
                MsgBox("Your search string is too short." & vbCrLf & _
                        "Please try again with a longer Name.", , _
                        "Name search string too short")
            End If

        Else

            MsgBox("There is no Ranking page loaded" & vbCrLf & _
                    "please load a page and try again", , _
                    "No page loaded")
        End If

    End Sub

    Private Sub TextBox1_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyUp

    End Sub

    Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click

        If Not DataGridView1.DataSource Is Nothing Then

            If TextBox2.Text.Length > 0 Then

                Dim searchstring As String = TextBox2.Text

                resulttable = New DataTable

                If Not searchInDatatable(webtable, resulttable, "ID", searchstring, True) Then

                    Exit Sub

                End If

                Form2.DataGridView1.DataSource = resulttable
                Form2.DataGridView1.Columns("ID").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
                Form2.DataGridView1.Columns("Prestige").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
                Form2.Show()
            Else
                MsgBox("Your search string is too short." & vbCrLf & _
                        "Please try again with a longer ID.", , _
                        "ID search string too short")
            End If

        Else

            MsgBox("There is no Ranking page loaded" & vbCrLf & _
                    "please load a page and try again", , _
                    "No page loaded")
        End If



    End Sub

    Private Sub TextBox2_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox2.KeyUp
        If e.KeyCode = Keys.Enter Then Button5_Click(vbNull, System.EventArgs.Empty)
    End Sub


    Private Sub Button6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Form2.Show()
    End Sub

    Private Sub Button6_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button6.Click

        If Not DataGridView1.DataSource Is Nothing Then

            Dim searchstring As String = "ed"

            resulttable = New DataTable

            If Not searchInDatatable(webtable, resulttable, "Name", searchstring, True) Then

                Exit Sub

            End If

            Form2.DataGridView1.DataSource = resulttable
            Form2.DataGridView1.Columns("ID").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
            Form2.DataGridView1.Columns("Prestige").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
            Form2.Show()

        End If

    End Sub

    Public Function searchInDatatable(ByRef Search_DT As DataTable, ByRef Result_DT As DataTable, ByVal fieldname As String, ByVal searchstring As String, ByVal sortdecending As Boolean) As Integer
        searchInDatatable = False

        Dim resultrows = From resulting_rows In Search_DT.AsEnumerable Where resulting_rows.Field(Of String)(fieldname).ToLower.Contains(searchstring.ToLower) Select resulting_rows

        Result_DT = New DataTable
        Result_DT = Search_DT.Clone

        If sortdecending Then

            Dim sortedrows = From unsortedrows In resultrows Order By unsortedrows!ID Descending

            If sortedrows.Count > 0 Then
                Result_DT = sortedrows.CopyToDataTable
                searchInDatatable = True
            Else
                MsgBox("The " & searchstring & " you're trying to find is not found in current ranks" & vbCrLf & _
                        "Please try again with a different ID" & searchstring, , _
                        searchstring & " not found")
            End If

        Else
            If resultrows.Count > 0 Then
                Result_DT = resultrows.CopyToDataTable
                searchInDatatable = True
            Else
                MsgBox("The " & searchstring & " you're trying to find is not found in current ranks" & vbCrLf & _
                        "Please try again with a different ID" & searchstring, , _
                        searchstring & " not found")
            End If


        End If

    End Function

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load




        updman.UpdateSource = New NAppUpdate.Framework.Sources.SimpleWebSource("https://dl.dropbox.com/u/97597963/AutoUpdater.NET_AppCast.xml") '// provided is the URL for the updates feed
        updman.ReinstateIfRestarted()
        'AddHandler updman.ReportProgress, Me.updlogger
    End Sub

    Public Sub updlogger(ByVal currentStatus As Common.UpdateProgressInfo)
        Console.WriteLine(currentStatus.Message.ToString & " -- updlogger")
    End Sub


    Private Sub Form1_Shown(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Shown
        Dim dirinfo As New IO.DirectoryInfo(Application.LocalUserAppDataPath)
        Dim dirinfofiles As IO.FileInfo() = dirinfo.GetFiles("*.csv")

        If dirinfofiles.Count > 0 Then
            If MsgBox("Load last-accessed local ranking database?", vbOKCancel, "Load last Database? ") = vbOK Then
                Me.Enabled = False
                Dim firstfileinfo As IO.FileInfo = dirinfofiles(0)

                For Each fileinfo As IO.FileInfo In dirinfofiles

                    If DateTime.Compare(firstfileinfo.LastAccessTime, fileinfo.LastAccessTime) <= 0 Then
                        firstfileinfo = fileinfo
                    End If
                Next

                localtable.loadCSVFileIntoTable(firstfileinfo.FullName)
                Label6.Text = firstfileinfo.Name
                DataGridView2.DataSource = localtable
                DataGridView2.Columns("ID").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
                DataGridView2.Columns("Prestige").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
            End If
            Me.Enabled = True
        End If
    End Sub


    Private Sub CheckForUpdatesToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckForUpdatesToolStripMenuItem.Click
        Me.Enabled = False


        If updman.State = UpdateManager.UpdateProcessState.NotChecked Then
            updman.CheckForUpdates()
            Console.WriteLine(updman.UpdatesAvailable.ToString + " Updates available")
        End If

        If updman.UpdatesAvailable > 0 Then

            If MsgBox(String.Format("Updates are available to your software ({0} total)." & vbCrLf & _
          "Do you want to download and apply them?", updman.UpdatesAvailable), _
         MsgBoxStyle.OkCancel, "Updates available") = vbOK Then

                MsgBox("Preparing updates.")
                updman.PrepareUpdates()
                MsgBox("Applying updates.")
                updman.ApplyUpdates(True)

            End If
        Else
            MsgBox("No updates available at this time", vbOK, "No updates")
        End If
        Me.Enabled = True
    End Sub


    Private Sub setupDGview(ByRef DGview As DataGridView, ByRef Datat As DataTable)
        DGview.DataSource = Datat

        setupDGcolumn(DGview, "Position", True, False)
        setupDGcolumn(DGview, "Name", True, False)
        setupDGcolumn(DGview, "ID", True, True)
        setupDGcolumn(DGview, "Rank", True, False)
        setupDGcolumn(DGview, "Prestige", True, True)
        setupDGcolumn(DGview, "Additional info", False, False)
    End Sub

    Private Sub setupDGcolumn(ByRef dataGridView As DataGridView, ByVal column As String, ByVal locked As Boolean, ByVal rightalign As Boolean)
        With dataGridView.Columns(column)
            If rightalign Then .DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
            .ReadOnly = locked

        End With

    End Sub

End Class
